package org.openfans.web;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Facade;
import org.openfans.domain.Fans;
import org.openfans.domain.Group;
import org.openfans.util.ThreadFans;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class GroupFormController extends SimpleFormController {
	private Facade facade = null;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	public GroupFormController() {
		setCommandName("group");
		setCommandClass(Group.class);
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Group group = (Group) command;

		Fans fans = ThreadFans.get();
		if (request.getParameter("delete") != null) {
			facade.removeGroup(group);

		} else {
			if (group.getGroupId() != 0) {// 已经存在
				facade.saveGroup(group);
			} else {
				group.setCreator(fans);
				group.setCreateDate(new Date());
				facade.saveGroup(group);
			}
		}
		return new ModelAndView("redirect:group/"
				+ group.getGroupId());
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		ThreadFans.authorize();
		String groupId = request.getParameter("id");

		if ((groupId != null) && !groupId.equals("0")) {
			return (Group) facade.getGroup(Integer.parseInt(groupId));
		} else {
			Group group = new Group();
			return group;
		}
	}

}
